package com.mchat.common.dao;

import com.mchat.common.domain.FileHash;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import lombok.RequiredArgsConstructor;
import org.reactivestreams.Publisher;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@RequiredArgsConstructor
@Component
public class FileHashDAO {
    private final DatabaseClient databaseClient;
    public Mono<String>getFileName(String hash){
        return databaseClient.sql("select file from tb_hash where hash=:hash")
                .bind("hash",hash)
                .map(row->row.get("0",String.class))
                .one();
    }
    public Mono<Long> batchSave(List<FileHash> list) {
        String sql = """
        insert into tb_hash (hash, "file") values ($1, $2)
        on conflict (hash) do nothing 
    """;

        return databaseClient.inConnection(conn -> {

            Statement statement = conn.createStatement(sql);
            for (int i = 0; i < list.size()-1; i++) {
                FileHash fileHash = list.get(i);
                statement.bind(0,fileHash.getFileHash())
                        .bind(1,fileHash.getFileName())
                        .add();
            }
            FileHash fileHash = list.get(list.size() - 1);
            statement.bind(0,fileHash.getFileHash())
                    .bind(1,fileHash.getFileName());
            return Flux.from(statement.execute()).flatMap(Result::getRowsUpdated).reduce(0L,Long::sum);
        });

    }
}
